#pragma once
#include "windows.h"
#include <assert.h>

class ITimer
{
public:
	virtual HRESULT timerFunc(LPVOID pragma) = 0;
};

template<class T>
class CTimer
{
public:
	CTimer(void);
	~CTimer(void)
	{
		if (m_thread!=NULL)
		{
			CloseHandle(m_thread);
		}		
		stopTimer();
	}
public:
	CTimer(T*obj)
	{
		m_obj = obj;
		assert(m_obj);
	}
	bool startTimer(DWORD timeVal)
	{
		m_timerVal = timeVal;
		DWORD dwThread=0;
		m_thread = CreateThread(NULL,NULL,run,this,NULL,&dwThread);
		if (m_thread == NULL)
		{
			return false;
		}
		m_bRunning = true;
		return true;
	}
	void stopTimer()
	{
		m_bRunning = false;
	}
	static DWORD WINAPI run(LPVOID pragma)
	{
		CTimer *pThis = (CTimer*)pragma;

		while (pThis->m_bRunning)
		{
			Sleep(pThis->m_timerVal);
			pThis->m_obj->timerFunc(pragma);
		}
		return 0;
	}
private:
	T *				m_obj;
	DWORD			m_timerVal;
	HANDLE			m_thread;
	bool			m_bRunning;
};
